<template>
  <div class="select-image-container">
    <el-checkbox-group
      v-if="isEdit === false"
      v-model="selectImgList"
      :min="imageListSelectMin"
      :max="imageListSelectMax"
    >
      <el-tabs v-model="imageListQuery.category_id" tab-position="left" @tab-click="handleTabClick">
        <el-tab-pane v-for="(item) in tabPaneTitle" :key="'select_image_tab_pane' + item.id" :name="item.id" :label="item.name">
          <el-upload
            ref="imageListUpload"
            :action="uploadImageListUrl"
            list-type="picture-card"
            :multiple="true"
            :headers="uploadHeaders"
            :data="uploadData"
            accept="image/*"
            :file-list="imgList"
            :on-success="imgListUploadSuccess"
            :on-error="imgListUploadError"
            :before-upload="imgListBeforeUpload"
            class="tn-upload-image-list"
          >
            <i slot="default" class="el-icon-plus" />
            <div slot="file" slot-scope="{ file }" class="img-center">
              <el-checkbox :key="file.url" :label="file.url" class="img-list-checkbox" />
              <el-image
                class="el-upload-list__item-thumbnail"
                :src="file.img_url || loadingImage"
                alt="图鸟"
                fit="scale-down"
              />
              <span class="img-list-name">{{ file.name }}</span>
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handleImageListPictureCardPreview(file)"
                >
                  <i class="el-icon-zoom-in" />
                </span>
                <span
                  class="el-upload-list__item-delete"
                  @click="handleImageListDownload(file.img_url)"
                >
                  <i class="el-icon-download" />
                </span>
                <span
                  class="el-upload-list__item-delete"
                  @click="handleImageListRemove(file.id)"
                >
                  <i class="el-icon-delete" />
                </span>
              </span>

            </div>
          </el-upload>
        </el-tab-pane>
      </el-tabs>
    </el-checkbox-group>
    <div v-else>
      <el-tabs v-model="imageListQuery.category_id" tab-position="left" @tab-click="handleTabClick">
        <el-tab-pane v-for="(item) in tabPaneTitle" :key="'select_image_tab_pane' + item.id" :name="item.id" :label="item.name">
          <el-upload
            ref="imageListUpload"
            :action="uploadImageListUrl"
            list-type="picture-card"
            :multiple="true"
            :headers="uploadHeaders"
            :data="uploadData"
            accept="image/*"
            :file-list="imgList"
            :on-success="imgListUploadSuccess"
            :on-error="imgListUploadError"
            :before-upload="imgListBeforeUpload"
            class="tn-upload-image-list"
          >
            <i slot="default" class="el-icon-plus" />
            <div slot="file" slot-scope="{ file }" class="img-center">
              <el-image
                class="el-upload-list__item-thumbnail"
                :src="file.img_url || loadingImage"
                alt="图鸟"
                fit="scale-down"
              />
              <span class="img-list-name">{{ file.name }}</span>
              <span
                class="el-upload-list__item-actions"
                @click="handleImageListPictureCardPreview(file)"
              >
                <span
                  class="el-upload-list__item-download"
                  @click.stop="handleImageListDownload(file.img_url)"
                >
                  <i class="el-icon-download" />
                </span>
                <span
                  class="el-upload-list__item-delete"
                  @click.stop="handleImageListRemove(file.id)"
                >
                  <i class="el-icon-delete" />
                </span>
                <span
                  class="el-upload-list__item-transform"
                  @click.stop="handleImageListTransform(file.id)"
                >
                  <i class="el-icon-guide" />
                </span>
              </span>
            </div>
          </el-upload>
        </el-tab-pane>
      </el-tabs>
    </div>
    <pagination
      v-show="imageListTotal > 0"
      :page-sizes="pageSize"
      :total="imageListTotal"
      :page.sync="imageListQuery.page"
      :limit.sync="imageListQuery.limit"
      @pagination="getImageListData"
    />
    <el-dialog
      :visible.sync="imageListPreviewDialogVisible"
      width="20%"
      append-to-body
    >
      <img width="100%" :src="imageListPreviewImgSrc" alt="">
    </el-dialog>
    <el-dialog
      v-if="isEdit === true"
      :title="'选择新栏目'"
      width="30%"
      :visible.sync="dialogCategoryVisible"
      :close-on-click-modal="false"
      :lock-scroll="true"
      :destory-on-close="true"
      append-to-body
    >
      <el-select
        v-model="changeCategoryData.category_id"
        placeholder="请选择需要移到的新栏目"
      >
        <el-option v-for="category_item in allCategoryName" :key="'select_image_category' + category_item.id" :value="category_item.id" :label="category_item.name" :disable="category_item.id === imageListQuery.category_id ? true : false" />
      </el-select>
      <el-button
        type="primary"
        @click="handleChangeCategory"
      >
        提交
      </el-button>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '../Pagination'
import { getToken } from '../../utils/auth'
import { getAllAtlasCategoryName } from '../../api/atlas-category'
import { getAtlasListData, deleteAtlasImage, changeCategory } from '../../api/atlas'
import { isArray } from '../../utils'
import store from '../../store'
import loadingImage from './image-loading.gif'

export default {
  name: 'TnSelectImage',
  components: { Pagination },
  props: {
    limit: {
      type: Number,
      default: 1
    },
    // eslint-disable-next-line vue/require-default-prop
    value: [String, Array],
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      imageValue: this.value,
      loadingImage: loadingImage,
      uploadImageListUrl: process.env.VUE_APP_BASE_URL + process.env.VUE_APP_IMAGE_LIST_UPLOAD_API,
      uploadHeaders: {
        Authorization: 'Bearer ' + getToken()
      },
      uploadData: {
        category_id: 0
      },
      uploadList: [],
      imgList: [],
      imageListPreviewDialogVisible: false,
      imageListPreviewImgSrc: '',
      imageListSelectMin: 0,
      imageListSelectMax: 1,
      imageListTotal: 0,
      imageListQuery: {
        page: 1,
        limit: 1,
        category_id: '-1'
      },
      tabPaneTitle: [
        { 'id': '-1', 'name': '全部' },
        { 'id': '0', 'name': '未分类' }
      ],
      allCategoryName: [],
      pageSize: [1],
      dialogCategoryVisible: false,
      changeCategoryData: {
        id: 0,
        category_id: ''
      },
      listObj: {}
    }
  },
  computed: {
    selectImgList: {
      get: function() {
        if (!this.imageValue || this.imageValue.length === 0) {
          return []
        }
        if (isArray(this.imageValue)) {
          const newValue = []
          this.imageValue.forEach((item, index) => {
            // console.log(index, item)
            newValue.push(item)
          })
          return newValue
        } else {
          return [this.imageValue]
        }
      },
      set: function(value) {
        // console.log(value)
        this.imageValue = []
        // console.log('nextTick', value)
        if (!value || value.length === 0) {
          this.imageValue = []
          return
        }
        if (this.limit === 1) {
          this.imageValue = value[0]
        } else {
          this.imageValue = value
        }
        this.changeVal(this.imageValue)
      }
    }
  },
  watch: {
    value(val) {
      // console.log('value', val)
      this.imageValue = val
    }
  },
  created() {
    this.getAllCategoryNameData()
    if (this.limit <= 1) {
      this.imageListSelectMin = 0
      this.imageListSelectMax = 1
      this.limit = 1
    } else {
      this.imageListSelectMin = 1
      this.imageListSelectMax = this.limit
    }
  },
  mounted() {
    this.$nextTick(() => {
      const upload_image_list_dom = document.querySelectorAll('.select-image-container .el-tabs__content')
      const upload_image_list_item_dom = document.querySelectorAll('.select-image-container .el-tabs__content .el-tab-pane:first-child .tn-upload-image-list .el-upload--picture-card')
      const list_dom_length = upload_image_list_dom.length
      const list_width = upload_image_list_dom[list_dom_length - 1].clientWidth
      const list_item_width = upload_image_list_item_dom[list_dom_length - 1].clientWidth
      // const body_height = document.querySelector('.app-main').clientHeight
      // console.log(body_height)

      let col_max = (Math.floor(list_width / (list_item_width + 6)) * 2) - 1
      col_max = col_max <= 0 ? 1 : col_max
      this.pageSize[0] = col_max
      this.imageListQuery.limit = col_max
      this.getImageListData()
      // console.log(list_width, list_item_width, col_max)
    })
  },
  methods: {
    changeVal(val) {
      // console.log('change', val)
      // this.$emit('changeModelVal', val)
      this.$emit('change', val)
    },
    handleImageListPictureCardPreview(file) {
      this.imageListPreviewDialogVisible = true
      this.imageListPreviewImgSrc = file.img_url
    },
    handleImageListDownload(file) {
      // console.log(file)

      window.open(file, 'target', '')
    },
    handleImageListRemove(id) {
      // console.log(id)
      const ids = []
      ids.push(id)
      this.$confirm('此操作将永久删除该数据，是否继续', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAtlasImage({ ids }).then(response => {
          this.$message({
            message: response.msg,
            type: 'success'
          })
          this.getImageListData()
        })
      }).catch(() => {})
    },
    imgListUploadSuccess(response, file, fileList) {
      // console.log(response, file, fileList)
      // const { data } = response
      this._setListObjSuceesFlag(file.uid)
      // 上传图片成功后重新获取图片列表数据(等待全部图片上传成功后再获取)
      if (this._checkAllSuccess() && response.errorCode === 0) {
        this.getImageListData()
      }
    },
    imgListUploadError(err, file, fileList) {
      if (err) {
        // console.log(err, file, fileList)
        // console.log(err.message)
        const message = err.message ? JSON.parse(err.message) : { msg: '上传图片失败', errorCode: 0 }
        this.$message({
          message: message.msg,
          type: 'error'
        })
        this._setListObjSuceesFlag(file.uid)
        // err = JSON.stringify(err.message)
        if (message.errorCode === 30000 || message.errorCode === 30001) {
          // console.log('upload reset')
          // to re-login
          this.$confirm('Token 已失效，请重新登陆', '确认登出', {
            confirmButtonText: '重新登陆',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          }).catch(() => {})
        }
      }
    },
    imgListBeforeUpload(file) {
      const fileName = file.uid
      this.listObj[fileName] = { hasSuccess: false, uid: file.uid }

      return true
    },
    toDefault() {
      this.uploadList = []
      // this.imgList = []
      this.listObj = {}
      this.imageValue = ''
    },
    handleTabClick(tabs) {
      // console.log(tabs)
      let category_id = parseInt(this.imageListQuery.category_id)
      category_id = category_id <= 0 ? 0 : category_id
      this.uploadData.category_id = category_id
      this.imageListQuery.page = 1
      this.getImageListData()
    },
    handleImageListTransform(id) {
      this.dialogCategoryVisible = true
      this.changeCategoryData.id = id
    },
    handleChangeCategory() {
      changeCategory(this.changeCategoryData).then(response => {
        this.$message({
          message: response.msg,
          type: 'success'
        })
        this.dialogCategoryVisible = false
        this.changeCategoryData.category_id = ''
        this.getImageListData()
      })
    },
    async getImageListData() {
      const { data, total } = await getAtlasListData(this.imageListQuery)
      // console.log(data)
      this.imageListTotal = total
      // this.imgList = []
      this.$nextTick().then(() => {
        this.imgList = []
        data.forEach((item, index) => {
          this.imgList.push({
            id: item.id,
            name: item.name,
            url: item.img_path,
            img_url: item.img_url,
            category_id: item.category_id
          })
        })
      })
    },
    getAllCategoryNameData() {
      getAllAtlasCategoryName().then(response => {
        const { data } = response
        // console.log(data)
        this.allCategoryName = data
        if (data && data.length > 0) {
          data.forEach(item => {
            this.tabPaneTitle.push({
              'id': '' + item.id,
              'name': item.name
            })
          })
        }
      })
    },
    _checkAllSuccess() {
      return Object.keys(this.listObj).every(item => this.listObj[item].hasSuccess)
    },
    _setListObjSuceesFlag(uid) {
      const objKeyArr = Object.keys(this.listObj)
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          this.listObj[objKeyArr[i]].hasSuccess = true
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.img-center {
  width: 100%;
  height: 100%;
  display: flex;
  // position: absolute;
  // top: 50%;
  // transform: translateY(-50%);
}
.img-list-checkbox {
  position: absolute;
  left: 7px;
  top: 7px;
}
.img-list-name {
  color: #000000;
  overflow: hidden;
  text-overflow: ellipsis;
  // -ms-text-overflow: ellipsis;
  // display: box;
  // display: -webkit-box;
  // line-clamp: 1;
  // -webkit-line-clamp: 1;
  // -webkit-box-orient: vertical;
  white-space: nowrap;
  position: absolute;
  left: 0px;
  bottom: 0px;
  width: 100%;
  text-align: center;
}
.el-checkbox >>> .el-checkbox__label {
  display: none !important;
}
.el-checkbox >>> .el-checkbox__input {
  zoom: 200%;
}
.el-upload-list--picture-card .el-upload-list__item-thumbnail {
  width: 100%;
  height: auto;
}
.tn-upload-image-list >>> .el-list-leave-active {
  transform: none !important;
  transition: none !important;
}
.tn-upload-image-list >>> .el-list-enter-active {
  transform: none !important;
  transition: none !important;
}
.tn-upload-image-list >>> .el-upload-list__item {
  margin-right: 6px !important;
}
</style>
